package com.stylefeng.guns.rest.common.utils;


/**
 * 输入校验的工具类
 *
 */

public class InputCheckUtil {

    /**
     * 检查个性id的合法性
     * @param id
     * @return
     */
    public static boolean isVaildId(String id){
        if (TextUtil.isEmpty(id)){
            return false;
        }
        if (id.length() < 8 || id.length() > 16){
            return false;
        }
        return true;
    }

    /**
     * 是否是合法的密码
     * @param pwd
     * @return
     */
    public static boolean isVaildPwd(String pwd){
        if (TextUtil.isEmpty(pwd)){
            return false;
        }
        if (!pwd.matches("^[0-9a-zA-Z]{6,16}$")){
            return false;
        }
        return true;
    }


    /**
     * 是否是合法的电话号码
     * @param phone
     * @return
     */
    public static boolean isVaildPhone(String phone){
        if (TextUtil.isEmpty(phone)){
            return false;
        }
        if (!phone.startsWith("1") || phone.length() != 11){
            return false;
        }
        return true;
    }

    /**
     * 判断是否是银行卡号
     * @param cardId
     * @return
     */
    public static boolean isVaildBankCard(String cardId) {
        char bit = getBankCardCheckCode(cardId
                .substring(0, cardId.length() - 1));
        if (bit == 'N') {
            return false;
        }
        return cardId.charAt(cardId.length() - 1) == bit;

    }

    private static char getBankCardCheckCode(String nonCheckCodeCardId) {
        if (nonCheckCodeCardId == null
                || nonCheckCodeCardId.trim().length() == 0
                || !nonCheckCodeCardId.matches("\\d+")) {
            // 如果传的不是数据返回N
            return 'N';
        }
        char[] chs = nonCheckCodeCardId.trim().toCharArray();
        int luhmSum = 0;
        for (int i = chs.length - 1, j = 0; i >= 0; i--, j++) {
            int k = chs[i] - '0';
            if (j % 2 == 0) {
                k *= 2;
                k = k / 10 + k % 10;
            }
            luhmSum += k;
        }
        return (luhmSum % 10 == 0) ? '0' : (char) ((10 - luhmSum % 10) + '0');
    }

}
